package com.grace.cms.general.controller;

import com.grace.cms.common.domain.BaseRecordEntity;
import com.grace.cms.common.domain.entity.CmsColumn;
import com.grace.cms.common.enums.RecordTypeEnums;
import com.grace.cms.general.cache.GeneralColumnCacheService;
import com.grace.cms.general.service.CommonInterface;
import com.grace.cms.general.taglib.ConfigTag;
import com.grace.common.config.GraceConfig;
import com.grace.common.core.controller.BaseController;
import com.grace.common.enums.GraceServerRoot;
import com.grace.common.properties.PropertyEnum;
import com.grace.common.utils.ServletUtils;
import java.nio.file.Paths;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;

/** 通用 */
public class CommonController extends BaseController {

    @Autowired
    protected GeneralColumnCacheService cmsColumnService;

    @Autowired
    protected ConfigTag configService;

    @Autowired
    private CommonInterface commonService;

    /**
     * 默认转发
     * 并附带参数
     * 
     * @param page
     * @return
     */
    protected String getPrefix(String themeName, String page, ModelMap mp) {
        mp.putAll(ServletUtils.getRequest().getParameterMap());
        return Paths.get(themeName,GraceServerRoot.THEME_TEMPLATE_DIR.getValue(),page).toString();
    }

    /**
     * 获取导航信息
     * 
     * @param themeName
     * @param propertyEnum
     * @return
     */
    protected CmsColumn getCmsColumn(String themeName, PropertyEnum propertyEnum) {
        CmsColumn cmsColumn = cmsColumnService.selectCmsColumnById(
                Long.parseLong(configService.getKeyDefaultEnum(themeName, propertyEnum)));
        return cmsColumn == null ? new CmsColumn() : cmsColumn;
    }

    /**
     * 获取导航信息
     * 
     * @param themeName 配置组别
     * @param key       配置key
     * @return
     */
    protected CmsColumn selectCmsColumnByIdItem(String themeName, String key) {
        CmsColumn cmsColumn = cmsColumnService.selectCmsColumnById(
                NumberUtils.toLong(configService.getKey(themeName, key), 0));
        return cmsColumn == null ? new CmsColumn() : cmsColumn;
    }

    protected void setCommonRecordParam(BaseRecordEntity recordEntity,String themeName,RecordTypeEnums recordType,boolean allowGuest){
        recordEntity.setThemeName(themeName);
        recordEntity.setOnlyCode(GraceConfig.getOnlyCode());
        recordEntity.setRecordType(recordType.ordinal());
        recordEntity.setCreateBy(commonService.getUserName(allowGuest));
        recordEntity.setRecordId(recordType.getPrefix(recordEntity.getRecordId()));
    }

}
